<?php


namespace App\Modules\Admin\Services\Seller;


use App\Exceptions\Seller\AuthTokenException;
use App\Exceptions\Seller\AuthException;
use App\Modules\Seller\Entities\Rabc\SellerAdmin;
use App\Services\Service;
use Illuminate\Support\Facades\Auth;

class SellerAuthServices extends Service
{

    protected $guard = 'seller_admin';

    public function login($request,$data){
        $auth = Auth::guard($this->guard);
        $token = $auth->attempt($data);

        if (!$token) throw new AuthException('认证失败！');
        $admin = $auth->user();
        switch ($admin->status) {
            case 0:
                throw new AuthException('该管理员尚未启用！', 0, $admin->admin_id);
                break;
            case 2:
                throw new AuthException('该管理员已禁用！', 0, $admin->admin_id);
                break;
        }

        return $this->respondWithToken($token);
    }

    public function me(){
        if (!$admin = Auth::guard($this->guard)->user()){
            throw new AuthTokenException('认证失败！');
        }

        $admin['roles'] = ['admin'];
        return $admin;
    }
    //获取权限
    public function getRabcList(){
        if (!$seller_admin = Auth::guard($this->guard)->user()){
            throw new AuthTokenException('认证失败！');
        }

        if ($seller_admin->is_admin==1){

        }
        $seller_admin = SellerAdmin::with(['roles.menus'])->find($seller_admin->seller_admin_id)->toArray();

        $menus = [];
        foreach (array_column($seller_admin['roles'], 'menus') as $item){
            $menus = array_merge($menus, $item);
        }

        return list_to_tree($menus);


    }

    /**
     * Get the token array structure.
     *
     * @param $token
     * @return array
     */
    protected function respondWithToken($token)
    {
        return [
            'access_token' => $token,
            'token_type'   => 'Bearer',
            'expires_time'   => time() + Auth::guard($this->guard)->factory()->getTTL() * 60*60*24
        ];
    }
}